//
//  BRMImageEditViewController.m
//  BrezzeSaaS
//
//  Created by macos on 15.3.22.
//  Copyright © 2022 Brezze GWG. All rights reserved.
//

#import "BRMImageEditViewController.h"
#import "BRMImageCollectionViewCell.h"
#import "TZImagePreviewController.h"
#import "TZImagePickerController.h"
#import <Photos/Photos.h>
#import <MobileCoreServices/MobileCoreServices.h>

#define kMaxPhoto 5

@interface BRMImageEditViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
{
//    QMUIButton *_editBtn;
}
@property (nonatomic,strong) UICollectionView *myCollection;

@property (nonatomic,assign) BOOL isEdit;

@property (nonatomic,strong) NSMutableArray *dataList;

@property (nonatomic,strong) NSArray *oldImgs;

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@end

@implementation BRMImageEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
}

- (void)toEdit:(QMUIButton *)btn {
    
    if (btn.isSelected) {
        NSString *imgs = [self.imgs componentsJoinedByString:@","];
        [self blockDic:imgs];
        btn.selected = NO;
        self.isEdit = NO;
        return;
    }
    self.isEdit = !self.isEdit;
    btn.selected = self.isEdit;
    self.oldImgs = self.imgs;
    
}

- (void)setIsEdit:(BOOL)isEdit {
    _isEdit = isEdit;
    
    [self.myCollection reloadData];
}

- (void)deleteImage:(NSInteger)index {
    
    NSLog(@"%ld",index);
//    [self.dataList removeObjectAtIndex:index];
//
//    [self.myCollection reloadData];
    NSMutableArray *imgs = [NSMutableArray arrayWithArray:self.imgs];
    [imgs removeObjectAtIndex:index];
    self.imgs = imgs;
    
    NSString *imgstr = [self.imgs componentsJoinedByString:@","];
    [self blockDic:imgstr];
}

- (void)setImgs:(NSArray *)imgs {
    _imgs = imgs;
    [self.dataList removeAllObjects];
    for (NSString *path in imgs) {
        NSString *url = [NSString stringWithFormat:@"%@%@",USERManager.filesSever,path];
        [self.dataList addObject:url];
    }
    [self.myCollection reloadData];
}

//- (void)pop {
//
//    if (self.isEdit) {
//
//        BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"Public_notice") subTitle:Localized(@"Edit_warringDelete") cancelStr:Localized(@"Public_cancel") succStr:Localized(@"public_confirm") cancelAction:^{
//
//        } successAction:^{
//
//            [super pop];
//
//        } showBC:YES];
//
//        [self.view addSubview:alertV];
//
//        return;
//    }
//    [super pop];
//}

- (void)blockDic:(NSString *)imgs {
    if (self.updateImgsBlock) {
        self.updateImgsBlock(@{@"text":imgs,@"title":Localized(@"shop_shopPhoto")});
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
//    CGFloat offset = 28;
    CGFloat cardWith = (kScreenWidth-2*27) / 3.0;
//    CGFloat cardHeight = 160;
    return CGSizeMake(cardWith, cardWith);
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (self.dataList.count < kMaxPhoto) {
        return self.dataList.count + 1;
    }
    return self.dataList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    BRMImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BRMImageCollectionViewCell" forIndexPath:indexPath];
    
    NSInteger index = indexPath.row;
    cell.deleBtn.hidden = NO;
    if (self.dataList.count < kMaxPhoto) {
        cell.isNoraml = indexPath.row != 0;
        if (indexPath.row == 0) {
            cell.deleBtn.hidden = YES;
            
            return cell;
        }
        index -= 1;
    }else {
        
        cell.isNoraml = YES;
    }
    
    NSString *url = self.dataList[index];
    [cell.img sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:UIImageMake(@"pic_station")]; //pic_station
    
    WS(weakSelf);
    cell.deleToDo = ^{
        [weakSelf deleteImage:index];
    };
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (self.dataList.count < kMaxPhoto && indexPath.row == 0) {
        
        [self showUploadSheet];
        return;
    }
    NSInteger index = indexPath.row;
    if (self.dataList.count < kMaxPhoto) index -= 1;
    
    BRMImageCollectionViewCell *cell = (BRMImageCollectionViewCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:0]];
    
    [self clickImg:index imageView:cell.img];
    
}

- (void)showUploadSheet {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:Localized(@"public_album") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        [self pushTZImagePickerController];
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:Localized(@"public_camera") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:Localized(@"public_cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)uploadHeader:(NSData*)data{
    
    [BRHud showHud];
    WS(weakSelf);
    [BRAPI uploadFiles:data beginBlock:^{

    } successBlock:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:@{}];
        
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code != 0) {
            [BRHud hidden];
            NSLog(@"%@",responseObject[@"message"])
            return;
        }
        NSString *logoURL = responseObject[@"data"][@"value"];
        dic[@"icon"] = logoURL;
        NSMutableArray *new = [NSMutableArray arrayWithArray:weakSelf.imgs];
        [new addObject:logoURL];
        weakSelf.imgs = new;
        NSString *imgsStr = [new componentsJoinedByString:@","];
        [weakSelf blockDic:imgsStr];
        
        [BRHud hidden];
        
    } failureBlock:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [BRHud hidden];
    }];
    
    
}

#pragma mark - UI --
- (void)setUI {
    
    [self br_createTop:Localized(@"shop_shopPhoto")];
    self.view.backgroundColor = kColorBGF5;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 最小行间距，默认是0
    flowLayout.minimumLineSpacing = 10;
    // 最小左右间距，默认是10
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 16, 10, 16);
    
    UICollectionView *collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,kScreenWidth,kScreenHeight) collectionViewLayout:flowLayout];
    //collectView.pagingEnabled = YES;
    collectView.backgroundColor = UIColorClear;
//    collectView.contentInset = UIEdgeInsetsMake(0,0,0,0);
    collectView.showsVerticalScrollIndicator = NO;
    collectView.dataSource = self;
    collectView.delegate = self;
    
    [collectView registerNib:[UINib nibWithNibName:NSStringFromClass([BRMImageCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"BRMImageCollectionViewCell"];
    
    [self.view addSubview:collectView];
    [collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kSafeAreaTopHeight);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    self.myCollection = collectView;
    
}

- (NSMutableArray *)dataList {
    
    if (_dataList == nil) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

#pragma mark - TZImagePickerController --

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        // 允许用户选择取消或前往系统设置（用户主动点击才跳转，符合 Apple 审核要求）
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"Permission_Camera_title") message:Localized(@"Permission_Camera_Message") preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Permission_Back") style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Permission_ToSeting") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 用户主动点击"前往系统设置"按钮时才跳转
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        // 允许用户选择取消或前往系统设置（用户主动点击才跳转，符合 Apple 审核要求）
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"Permission_Photos_title") message:Localized(@"Permission_Photos_Message") preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Permission_Back") style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"Permission_ToSeting") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 用户主动点击"前往系统设置"按钮时才跳转
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];

            [mediaTypes addObject:(NSString *)kUTTypeImage];

        
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (CGRect)br_cropFrame {
    NSInteger left = 0;
    NSInteger widthHeight = self.view.mj_w - 2 * left;
    NSInteger height  =  widthHeight * 9 / 16;
    NSInteger top = (self.view.mj_h - height) / 2;
    
    return CGRectMake(left, top, widthHeight, height);
}

- (void)pushTZImagePickerController {
   
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    
// - 五类个性化设置，这些参数都可以不传，此时会走默认设置
   
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.allowTakeVideo = NO;   // 在内部显示拍视频按
    
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
 
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
  
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = YES;
    imagePickerVc.needCircleCrop = NO;
    // 设置竖屏下的裁剪尺寸
    imagePickerVc.cropRect = [self br_cropFrame];
    imagePickerVc.scaleAspectFillCrop = YES;
    // 设置横屏下的裁剪尺寸
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    // 自定义gif播放方案
    
    NSString *language = [BRLanguageManager share].language;
    // 设置首选语言 / Set preferred language
    imagePickerVc.preferredLanguage = language;
    // done 按钮颜色
    imagePickerVc.oKButtonTitleColorNormal = UIColor.whiteColor;
    
#pragma mark - 到这里为止
    WS(weakSelf);
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        [weakSelf toUpdateImg:photos.firstObject];
        
    }];
    
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.preferredLanguage = [BRLanguageManager share].language;
    tzImagePickerVc.sortAscendingByModificationDate = YES; //时间排序降序
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSDictionary *meta = [info objectForKey:UIImagePickerControllerMediaMetadata];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image meta:meta location:nil completion:^(PHAsset *asset, NSError *error){
            [tzImagePickerVc hideProgressHUD];
            if (error) {
                NSLog(@"图片保存失败 %@",error);
            } else {
                TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                //                if (self.allowCropSwitch.isOn) { // 允许裁剪,去裁剪
                TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                    [self toUpdateImg:cropImage];
                }];
                imagePicker.allowPickingImage = YES;
                imagePicker.needCircleCrop = NO;
                imagePicker.allowCrop = YES;
                imagePicker.cropRect = [self br_cropFrame];
                [self presentViewController:imagePicker animated:YES completion:nil];

            }
        }];
    }

}

- (void)toUpdateImg:(UIImage *)image {
    NSData *uploadData = UIImageJPEGRepresentation(image, 1);;
    [self uploadHeader: uploadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
//        _imagePickerVc.naviBgColor = kColorMain;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
            
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}

#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    // NSLog(@"cancel");
}

// The picker should dismiss itself; when it dismissed these handle will be called.
// You can also set autoDismiss to NO, then the picker don't dismiss itself.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 你也可以设置autoDismiss属性为NO，选择器就不会自己dismis了
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
//    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
//    _selectedAssets = [NSMutableArray arrayWithArray:assets];
//    _isSelectOriginalPhoto = isSelectOriginalPhoto;
//    [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));

    // 1.打印图片名字
//    [self printAssetsName:assets];
    // 2.图片位置信息
//    for (PHAsset *phAsset in assets) {
//        NSLog(@"location:%@",phAsset.location);
//    }

    // 3. 获取原图的示例，用队列限制最大并发为1，避免内存暴增
//    self.operationQueue = [[NSOperationQueue alloc] init];
//    self.operationQueue.maxConcurrentOperationCount = 1;
//    for (NSInteger i = 0; i < assets.count; i++) {
//        PHAsset *asset = assets[i];
//        // 图片上传operation，上传代码请写到operation内的start方法里，内有注释
//        TZImageUploadOperation *operation = [[TZImageUploadOperation alloc] initWithAsset:asset completion:^(UIImage * photo, NSDictionary *info, BOOL isDegraded) {
//            if (isDegraded) return;
//            NSLog(@"图片获取&上传完成");
//        } progressHandler:^(double progress, NSError * _Nonnull error, BOOL * _Nonnull stop, NSDictionary * _Nonnull info) {
//            NSLog(@"获取原图进度 %f", progress);
//        }];
//        [self.operationQueue addOperation:operation];
//    }
}

/// 如果用户选择了某张照片下面的代理方法会被执行
/// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
/// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
- (void)imagePickerController:(TZImagePickerController *)picker didSelectAsset:(PHAsset *)asset photo:(UIImage *)photo isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
//    [_selectedAssets addObject:asset];
//    [_selectedPhotos addObject:photo];
//    [self.collectionView reloadData];
    NSLog(@"如果用户选择了某张照片下面的代理方法会被执行 imagePickerController");
}

/// 如果用户取消选择了某张照片下面的代理方法会被执行
/// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
/// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
- (void)imagePickerController:(TZImagePickerController *)picker didDeselectAsset:(PHAsset *)asset photo:(UIImage *)photo isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
//    int index = -1;
//    for (int i = 0; i < _selectedAssets.count; i++) {
//        if ([_selectedAssets[i] isEqual:asset]) {
//            index = i;
//        }
//    }
//    if (index > -1) {
//        [_selectedAssets removeObjectAtIndex:index];
//        [_selectedPhotos removeObjectAtIndex:index];
//        [self.collectionView reloadData];
//    }
}

// If user picking a video and allowPickingMultipleVideo is NO, this callback will be called.
// If allowPickingMultipleVideo is YES, will call imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
// 如果用户选择了一个视频且allowPickingMultipleVideo是NO，下面的代理方法会被执行
// 如果allowPickingMultipleVideo是YES，将会调用imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
//    _selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
//    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
//    // open this code to send video / 打开这段代码发送视频
//    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
//        // NSData *data = [NSData dataWithContentsOfFile:outputPath];
//        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
//        // Export completed, send video here, send by outputPath or NSData
//        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
//    } failure:^(NSString *errorMessage, NSError *error) {
//        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
//    }];
//    [_collectionView reloadData];
    // _collectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
}

// If allowEditVideo is YES and allowPickingMultipleVideo is NO, When user picking a video, this callback will be called.
// If allowPickingMultipleVideo is YES, video editing is not supported, will call imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
// 当allowEditVideo是YES且allowPickingMultipleVideo是NO是，如果用户选择了一个视频，下面的代理方法会被执行
// 如果allowPickingMultipleVideo是YES，则不支持编辑视频，将会调用imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingAndEditingVideo:(UIImage *)coverImage outputPath:(NSString *)outputPath error:(NSString *)errorMsg {
//    _isAllowEditVideo = YES;
//    self->_selectedPhotos = [NSMutableArray arrayWithArray:@[coverImage]];
//    self->_selectedAssets = [NSMutableArray arrayWithArray:@[[NSURL fileURLWithPath:outputPath]]];
//    if (outputPath) {
//        // NSData *data = [NSData dataWithContentsOfFile:outputPath];
//        NSLog(@"视频导出到本地完成,outputPath为:%@",outputPath);
//        // Export completed, send video here, send by outputPath or NSData
//        // 导出完成，在这里写上传代码，通过路径或者通过NSData上传
//    } else {
//        NSLog(@"视频导出失败:%@",errorMsg);
//    }
//    [self.collectionView reloadData];
}

// If user fail to save edited, this callback will be called.
// 如果用户保存编辑好的视频失败，将会调用
- (void)imagePickerController:(TZImagePickerController *)picker didFailToSaveEditedVideoWithError:(NSError *)error {
    NSLog(@"编辑后的视频自动保存到相册失败:%@",error.description);
}

// If user picking a gif image and allowPickingMultipleVideo is NO, this callback will be called.
// If allowPickingMultipleVideo is YES, will call imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
// 如果用户选择了一个gif图片且allowPickingMultipleVideo是NO，下面的代理方法会被执行
// 如果allowPickingMultipleVideo是YES，将会调用imagePickerController:didFinishPickingPhotos:sourceAssets:isSelectOriginalPhoto:
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(PHAsset *)asset {
//    _selectedPhotos = [NSMutableArray arrayWithArray:@[animatedImage]];
//    _selectedAssets = [NSMutableArray arrayWithArray:@[asset]];
//    [_collectionView reloadData];
}

// Decide album show or not't
// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(PHFetchResult *)result {
    /*
    if ([albumName isEqualToString:@"个人收藏"]) {
        return NO;
    }
    if ([albumName isEqualToString:@"视频"]) {
        return NO;
    }*/
    return YES;
}

// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanBeDisplayed:(PHAsset *)asset {
    /*
    switch (asset.mediaType) {
        case PHAssetMediaTypeVideo: {
            // 视频时长
            // NSTimeInterval duration = phAsset.duration;
            return NO;
        } break;
        case PHAssetMediaTypeImage: {
            // 图片尺寸
            if (asset.pixelWidth > 3000 || asset.pixelHeight > 3000) {
                 return NO;
            }
            return YES;
        } break;
        case PHAssetMediaTypeAudio:
            return NO;
            break;
        case PHAssetMediaTypeUnknown:
            return NO;
            break;
        default: break;
    }
     */
    return YES;
}

// Decide asset can be selected
// 决定照片能否被选中
- (BOOL)isAssetCanBeSelected:(PHAsset *)asset {
    /*
    switch (asset.mediaType) {
        case PHAssetMediaTypeVideo: {
            // 视频时长
            // NSTimeInterval duration = phAsset.duration;
            return NO;
        } break;
        case PHAssetMediaTypeImage: {
            // 图片尺寸
            if (asset.pixelWidth > 3000 || asset.pixelHeight > 3000) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"不支持选择超大图片" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self.presentedViewController presentViewController:alertController animated:YES completion:nil];
                return NO;
            }
            return YES;
        } break;
        case PHAssetMediaTypeAudio:
            return NO;
            break;
        case PHAssetMediaTypeUnknown:
            return NO;
            break;
        default: break;
    }
     */
    return YES;
}


#pragma mark - img picker --
- (void)clickImg:(NSInteger)index imageView:(nonnull UIImageView *)logImgView {
    
    TZImagePickerController *imagePickerVc = [self createTZImagePickerController];
    imagePickerVc.maxImagesCount = 1;
    imagePickerVc.showSelectBtn = NO;
    [imagePickerVc setPhotoPreviewPageDidLayoutSubviewsBlock:^(UICollectionView *collectionView, UIView *naviBar, UIButton *backButton, UIButton *selectButton, UILabel *indexLabel, UIView *toolBar, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel) {
        if (naviBar) {
            [naviBar removeFromSuperview];
            naviBar = nil;
        }
        if (backButton) {
            [backButton removeFromSuperview];
            backButton = nil;
        }
        if (numberLabel) {
            [numberLabel removeFromSuperview];
            numberLabel = nil;
        }
        if (toolBar) {
            [toolBar removeFromSuperview];
            toolBar = nil;
        }
        if (numberImageView) {
            [numberImageView removeFromSuperview];
            numberImageView = nil;
        }
        if (doneButton) {
            [doneButton removeFromSuperview];
            doneButton = nil;
        }
    }];
    
    NSArray *urlArr = [self.dataList mutableCopy];
    TZImagePreviewController *previewVc = [[TZImagePreviewController alloc] initWithPhotos:urlArr currentIndex:index tzImagePickerVc:imagePickerVc];
    [previewVc setBackButtonClickBlock:^(BOOL isSelectOriginalPhoto) {
        NSLog(@"预览页 返回 isSelectOriginalPhoto:%d", isSelectOriginalPhoto);
    }];
    

    [previewVc setSetImageWithURLBlock:^(NSURL *URL, UIImageView *imageView, NSInteger index, void (^completion)(void)) {
        [self configImageView:imageView URL:URL index:index completion:completion];
    }];
    
    [previewVc setDoneButtonClickBlock:^(NSArray *photos, BOOL isSelectOriginalPhoto) {
        
        NSLog(@"预览页 完成 isSelectOriginalPhoto:%d photos.count:%zd", isSelectOriginalPhoto, photos.count);
    }];
    
    BRWeakObj(previewVc);
    previewVc.updateCurreIndex = ^(NSInteger index) {
        BRStrong(previewVc);
        [previewVc updateTitleString:@""];
//        [self.myCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    };
    
    [self scaleOfCell:logImgView text:@"" VC:previewVc];
    
    WS(weakSelf);
    previewVc.signOutBlock = ^(UIImageView *imageView, NSInteger cureIndex) {
        
        [weakSelf scaleOfVCImage:imageView index:cureIndex cellIndex:0];
    };
}

- (void)scaleOfCell:(UIImageView *)image text:(NSString *)text VC:(TZImagePreviewController *)previewVc{
    
    UIImage *imageN = image.image;
    if (!imageN) {
        NSLog(@"图片异常");
        return;
    }
    
    __block UIImageView *imageView = [[UIImageView alloc] initWithFrame:[image convertRect: image.bounds toView:image.window]];
    imageView.backgroundColor = [UIColor blackColor];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.alpha = 0;
    [self.view addSubview:imageView];
   
//    if (!imageN) {
//        imageN = UIImageMake(kDefaultImg);
//    }
    imageView.image = imageN;
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = self.view.bounds;
        if (imageView.image.size.height/imageView.image.size.width < kScreenHeight / kScreenWidth) {
            imageView.frame = CGRectMake(0, (kScreenHeight - imageView.image.size.height * (kScreenWidth / imageView.image.size.width)) / 2, kScreenWidth, imageView.image.size.height * (kScreenWidth / imageView.image.size.width));
        }else{
            
            imageView.frame = CGRectMake((kScreenWidth - imageView.image.size.width * (kScreenHeight / imageView.image.size.height)), 0, imageView.image.size.width * (kScreenHeight / imageView.image.size.height), kScreenHeight);
        }
        imageView.alpha = 1;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        imageView = nil;
        [self pushViewController:previewVc animated:NO completion:^{
            
            [previewVc updateTitleString:text];
        }];
    }];
}

- (void)scaleOfVCImage:(UIImageView *)image index:(NSInteger)index cellIndex:(NSInteger)cellIndex {
    
    __block UIImageView *imageView = [[UIImageView alloc] initWithFrame:[image convertRect: image.bounds toView:image.window]];
    imageView.frame = self.view.bounds;
    imageView.backgroundColor = [UIColor blackColor];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.alpha = 1;
    [self.view addSubview:imageView];
    imageView.image = image.image;
//    [self.myCollection layoutIfNeeded];//横向布局，图片移动到指定图片后 需layoutIfNeeded，获取cell的准确位置
    NSInteger indexCurr = index;
    if (self.dataList.count < kMaxPhoto) {
        indexCurr += 1;
    }
    BRMImageCollectionViewCell *cell = (BRMImageCollectionViewCell *)[self.myCollection cellForItemAtIndexPath:[NSIndexPath indexPathForItem:indexCurr inSection:0]];
    
    CGRect frame = [cell.img convertRect:cell.img.bounds toView:self.view];
    [UIView animateWithDuration:0.3 animations:^{

        imageView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
        imageView.alpha = 0;
    } completion:^(BOOL finished) {
        [imageView removeFromSuperview];
        imageView = nil;
        
    }];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated completion: (void (^)(void))completion {
    [CATransaction setCompletionBlock:completion];
    [CATransaction begin];
    [self.navigationController pushViewController:viewController animated:animated];
    [CATransaction commit];
}

- (void)configImageView:(UIImageView *)imageView URL:(NSURL *)URL index:(NSInteger)index completion:(void (^)(void))completion{
    if ([URL.absoluteString.lowercaseString hasSuffix:@"gif"]) {
        // 先显示静态图占位
        [[SDWebImageManager sharedManager] loadImageWithURL:URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (!imageView.image) {
                imageView.image = image;
            }
        }];
        // 动图加载完再覆盖掉
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:URL options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            imageView.image = [UIImage sd_imageWithGIFData:data];
            if (completion) {
                completion();
            }
        }];
    } else {
        NSArray *urlArr = [self.dataList mutableCopy];
        NSString *url = urlArr[index];
        UIImage *image =  (UIImage *)[[SDImageCache sharedImageCache] imageFromCacheForKey:url];
        if (!image) {
            //展开后没有缓存优先显示默认图片
            image = UIImageMake(kDefaultImg);
        }
        [imageView sd_setImageWithURL:URL placeholderImage:image completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (completion) {
                completion();
            }
        }];
//        [imageView sd_setImageWithURL:URL completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//            if (completion) {
//                completion();
//            }
//        }];
    }
}

#pragma mark - TZImagePickerController

- (TZImagePickerController *)createTZImagePickerController {
    [TZImageManager manager].isPreviewNetworkImage = YES;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:kMaxPhoto columnNumber:4 delegate:self pushPhotoPickerVc:NO];
    
    imagePickerVc.naviBgColor = kColorMain;
//- 个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];

    imagePickerVc.allowPickingVideo = YES;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = YES;
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.allowPickingMultipleVideo = YES;


    imagePickerVc.needShowStatusBar = YES;
    imagePickerVc.showSelectBtn = NO;
//     imagePickerVc.preferredLanguage = @"zh-Hans";
    
    return imagePickerVc;
}

- (BOOL)forceEnableInteractivePopGestureRecognizer {
    // 屏蔽右滑返回
    return NO;

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
